package edu.buffalo.cse.cse486_586.service;

import java.util.Map;

import android.util.Log;
import edu.buffalo.cse.cse486_586.entity.PendingMessage;
import edu.buffalo.cse.cse486_586.entity.VoteMessage;
import edu.buffalo.cse.cse486_586.util.CommonUtil;

public class MessageProcessor {
	public final static String MESSAGE_SPLITTER = "/--/";
	private String pkg;

	protected MessageProcessor() {
		this.pkg = "";
	}

	public String getPkg() {
		return pkg;
	}

	public void setPkg(String pkg) {
		this.pkg = pkg;
	}

	/*
	 * Example: type/--/senderPortNumber_msgId/--/[vector]/--/data
	 */
	public PendingMessage processContentMessage() {
		PendingMessage pm = new PendingMessage();
		String tokens[] = pkg.split(MESSAGE_SPLITTER);

		if (CommonUtil.isNumeric(tokens[0])
				&& (Integer.parseInt(tokens[0]) == MessageBean.PENDING_MESSAGE || Integer
						.parseInt(tokens[0]) == MessageBean.FOREWARD_MESSAGE)
				&& tokens.length == 4) {
			String subToken[] = tokens[1].split("_");
			int senderPort = Integer.parseInt(subToken[0]);

			pm.setMessageId(tokens[1]);
			pm.setContent(tokens[3]);
			pm.setSenderPort(senderPort);

			if (Integer.parseInt(tokens[0]) == MessageBean.PENDING_MESSAGE) {
				pm.setForeward(false);
			} else {
				pm.setForeward(true);
			}

			int i = 0;
			String vectorTokens[] = tokens[2].split(",");
			// update the sender value in local vector
			Log.d("MessageProcessor", pm.getVector().toString());
			for (Map.Entry<Integer, Integer> item : pm.getVector().entrySet()) {
				pm.getVector().put(item.getKey(),
						Integer.parseInt(vectorTokens[i++]));
			}
			return pm;
		} else {
			return null;
		}
	}

	/*
	 * Example:
	 * type/--/senderPortNumber/--/senderPortNumber_msgId:purposal_total_sequencer
	 */
	public VoteMessage processVoteMessage() {
		VoteMessage vm = new VoteMessage();
		String tokens[] = pkg.split(MESSAGE_SPLITTER);
		if (CommonUtil.isNumeric(tokens[0])
				&& (Integer.parseInt(tokens[0]) == MessageBean.VOTE_MESSAGE || Integer
						.parseInt(tokens[0]) == MessageBean.FINAL_MESSAGE)
				&& tokens.length == 3) {
			vm.setSenderPort(Integer.parseInt(tokens[1]));
			String subTokens[] = tokens[2].split(":");
			vm.setVotedMessageId(subTokens[0]);
			vm.setPurposedSequence(subTokens[1]);
			
			if (Integer.parseInt(tokens[0]) == MessageBean.FINAL_MESSAGE) {
				vm.setFinal(true);
			} else {
				vm.setFinal(false);
			}
			
			return vm;
		} else {
			return null;
		}
	}
}
